<template>
  <div class="app-container">
    <el-form v-loading="formLoading" :model="postForm" :rules="rules" ref="postForm" label-width="220px" label-position="right">
      <el-form-item label="选择类别：">
        <el-radio-group v-model="catLevel" @change="selectCategory" :disabled="catLevelDisabled">
          <el-radio v-for="item in categoryOptions" :key="item.key" :label="item.key" :value="item.key">
            {{ item.value }}
           </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="!parentCatShow" label="选择一级类别：" prop="parentId">
        <el-select v-model="postForm.parentId" placeholder="请选择" style="width: 650px">
          <el-option v-for="item in parentOptions" :key="item.catId" :label="item.name" :value="item.catId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="parentCatShow" label="一级类别：" prop="name">
        <el-input v-model.trim="postForm.name" placeholder="请输入一级类别名称，不超过10个字" style="width: 650px"></el-input>
      </el-form-item>
      <el-form-item v-if="parentCatShow" label="是否首页显示：">
        <el-radio-group v-model="postForm.indexShow">
          <el-radio :label="0">
            否
          </el-radio>
          <el-radio :label="1">
            是
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="!parentCatShow" label="二级类别：" prop="name">
        <el-input v-model.trim="postForm.name" placeholder="请输入二级类别名称，不超过10个字" style="width: 650px"></el-input>
      </el-form-item>
      <el-form-item label="分类排序：" prop="sort">
        <el-input type="number" v-model.number="postForm.sort" style="width: 650px"></el-input>
      </el-form-item>
      <el-form-item label="分类图片(宽80*高80)：">
        <!-- <el-upload
          ref="upload"
          name="avatar"
          :action="imageUploadUrl"
          list-type="picture"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          :beforeUpload="handleBeforeUpload"
          :file-list="avatarList"
          :limit="1"
          :auto-upload="false"
          style="width: 420px">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        </el-upload> -->
        <div class="clearfix">
          <img class="fl margin-r" :src="postForm.avatar" @error="setDefultImg" width="100" height="100" alt="">
          <el-upload
            class="fl"
            ref="avatarUpload"
            name="avatar" 
            :action="imageUploadUrl"
            list-type="picture"
            :before-upload="handleBeforeUpload"
            :on-success="handleSuccess"
            :show-file-list="false"
            :auto-upload="true"
            style="width: 420px">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过3m</div>
          </el-upload>
        </div>
      </el-form-item>
      <!-- <el-form-item label="状态：">
        <el-checkbox v-model="postForm.status" :true-label=1 :false-label=0>开启(关闭后该分类不能再使用, 该分类下的商品不会下架)</el-checkbox>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-check" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getCourseCategory, createCourseCategory, updateCourseCategory, getParentCategories,getChildCategories } from '@/api/courseCategory'
// import imageComponent from '@/components/imageComponent'
// import ImageCropper from '@/components/ImageCropper'
import defultImg from '@/assets/defult270.png'
const postForm = {
  name: null,
  parentId: 0,
  sort: 0,
  avatar: '',
  status: 1
}

const validateNumber = (rule, value, callback) => {
  if (value && isNaN(value)) {
    callback('请输入正确的数值')
  } else {
    if (value < 0) {
      callback('请输入正确的数值')
    }
    callback()
  }
}

const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { max: 10, message: '最多不超过10个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '分类排序不能为空', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' }
  ]
}

const categoryOptions = [
  { key: 0, value: '一级类别' },
  { key: 1, value: '二级类别' }
]

export default {
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  // components: {
  //   imageComponent,
  //   ImageCropper
  // },
  data() {
    return {
      postForm: Object.assign({ indexShow:0 }, postForm),
      rules,
      formLoading: false,
      parentOptions: [],
      categoryOptions,
      catLevel: 0,
      avatarList: [],
      parentCatShow: true,
      catLevelDisabled: false,
      imageUploadUrl: process.env.BASE_API + '/common/courseCategories/imageUpload',
      imagecropperShow: false,
      imagecropperKey: 0
    }
  },
  created() {
    this.initOption()
    this.initData()
  },
  methods: {
    initOption() {
      getParentCategories().then(res => {
        this.parentOptions.push(...(res.data.data))
      }).catch(err => {
        console.log(err)
      })
    },
    initData() {
      if (this.isEdit) {
        const catId = this.$route.params.catId
        this.catLevelDisabled = true
        getCourseCategory(catId).then(res => {
          this.postForm = res.data.data
          if (this.postForm.parentId > 0) {
            this.catLevel = 1
            this.parentCatShow = false
          } else {
            if (this.postForm.avatar) {
              this.avatarList = [{ url: this.postForm.avatar }]
            }
          }
        }).catch(err => {
          console.log(err)
        })
      }
    },
    handleCreate() {
      createCourseCategory(this.postForm).then(res => {
        this.$notify({
          title: '提示',
          message: '提交成功!',
          type: 'success'
        })

        this.close()
      }).catch(err => {
        this.formLoading = false
        console.log(err)
      })
    },
    handleUpdate() {
      const catId = this.$route.params.catId
      updateCourseCategory(catId, this.postForm).then(res => {
        this.$notify({
          title: '提示',
          message: '提交成功!',
          type: 'success'
        })

        this.close()
      }).catch(err => {
        this.formLoading = false
        console.log(err)
      })
    },
    redirectTo() {
      this.$router.push({ name: 'courseCategory' })
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          if (!this.postForm.name) {
            this.$message.warning('请填写分类名称')
            return false
          }
          if (this.catLevel == 0 && !this.postForm.avatar) {
            this.$message.warning('请上传分类图片')
            return false
          }

          this.formLoading = true
          if (this.isEdit) {
            this.handleUpdate()
          } else {
            this.handleCreate()
          }
        } else {
          console.log('error submit!')
          return false
        }
      })
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleSuccess(response, file, fileList) {
      if (response.statusCode == 200) {
        this.postForm.avatar = response.data.imageUrl
        this.$message({
          message: '上传成功!',
          type: 'info'
        })
      } else {
        this.$message({
          message: '上传失败，请稍候再试!',
          type: 'info'
        })
      }
    },
    setDefultImg(e) {
      e.target.src = defultImg
    },
    handleBeforeUpload(file) {
      const isImg = file.type == 'image/jpeg' || file.type == 'image/png' || file.type == 'image/gif'
      if (!isImg) {
        this.$message.warning('上传图片只能是 JPG,GIF 或 PNG 格式')
      }
      const isLt3M = file.size / 1024 / 1024 < 3
      if (!isLt3M) {
        this.$message.error('上传图片大小不能超过 3MB!')
      }
      return isImg && isLt3M
    },
    selectCategory(val) {
      this.postForm = {
        name: null,
        parentId: 0,
        sort: 0,
        avatar: '',
        status: 1
      }
      this.avatarList = []
      this.$refs.postForm.clearValidate()

      if (val == 0) {
        // 一级分类
        this.parentCatShow = true
        this.postForm.avatar = ''
      } else {
        this.parentCatShow = false
        if (this.postForm.parentId == 0) {
          this.postForm.parentId = this.parentOptions[0].catId
        }
      }
    },
    close() {
      this.$store.dispatch('delVisitedViews', this.$route).then((views) => {
        const latestView = views.slice(-1)[0]
        if (latestView) {
          this.$router.push({ name: 'courseCategory' }) // latestView.path
        } else {
          this.$router.push('/')
        }
      })
    }
  }
}
</script>
